//
//  MWHomeController.m
//  XiRan-iOS
//
//  Created by Richfit on 2019/10/10.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWHomeController.h"
#import "MWHomeSearchController.h"
#import "MWGoodsDetailsController.h"

#import "MWNavigationController.h"
#import "MWPasswordLoginController.h"
#import "MWPasswordLoginController.h"

#import "MWHomeHeaderView.h"
#import "AboutMyCollectionReusableView.h"
#import "MWBannerCell.h"
#import "MWGoodsCell.h"

#import "MWFilterMenuView.h"

#import "MWBanner.h"
#import "MWGoods.h"
#import "MWAboutController.h"

@interface MWHomeController () <UICollectionViewDataSource, UICollectionViewDelegate, AboutMyCollectionReusableViewDelegate>

@property(strong, nonatomic) UICollectionView *collectionView;
@property(strong, nonatomic) MWFilterMenuView *filterView;

@property(strong, nonatomic) MWBanner *banner;
@property(strong, nonatomic) NSMutableArray *goodsArray;
@property(strong, nonatomic) NSMutableArray *filterArray;

@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@property(nonatomic, strong) NSString *filterStr;

@property(nonatomic, assign) CGFloat cellHeight;

@property (nonatomic, assign) CGFloat aboutMyCollectionReusableViewHeight;

@property (nonatomic, copy) NSString *contentString;

@property (nonatomic, strong) NSMutableArray *images;
@end

@implementation MWHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"homepage" defaultValue:@"首页"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSwitchNotification:) name:kSwitchPriceNotification object:nil];
    _page = 1;
    _size = 10;
    _requestMode = MWRequestModeRefresh;
    _filterStr = @"";
    
    [self setupPageSubviews];
    
    [self loadHomeFilter];
    [_collectionView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self checkVersion];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kSwitchPriceNotification object:nil];
}

-(void)searchAvtion:(UIButton *)sender {
    MWHomeSearchController *controller = [[MWHomeSearchController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)handleSwitchNotification:(NSNotification *)notification {
    [self refreshHomeGoods];
}

#pragma mark - 刷新数据
- (void)refreshHomeGoods {
    _page = 1;
    _requestMode = MWRequestModeRefresh;
    [self loadGoodsWithSearch:_filterStr page:_page size:_size];
}

#pragma mark - 加载更多数据
- (void)loadMoreHomeGoods {
    _page++;
    _requestMode = MWRequestModeLoadMore;
    [self loadGoodsWithSearch:_filterStr page:_page size:_size];
}

#pragma mark - 请求数据
- (void)loadGoodsWithSearch:(NSString *)search page:(NSInteger)page size:(NSInteger)size {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:search forKey:@"search"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", (long)size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kHomeGoodsUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        [self handleGoodsResult:responseObject];
        
    } failure:^(NSError *error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        
        NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        NSString *logStr =  [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:errorData options:kNilOptions error:nil];
        
        [self uploadLog:logStr];
        
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        if (code == 401) {
            NSString *msg = @"登录已过期，请重新登录！";
            UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [[NSNotificationCenter defaultCenter] postNotificationName:kLoginOverdueNotification object:nil];
                MWPasswordLoginController *controller = [[MWPasswordLoginController alloc] init];
                [self.navigationController pushViewController:controller animated:YES];
            }];
            [controller addAction:cancelAction];
            [weakSelf presentViewController:controller animated:YES completion:^{
                
            }];
        }
    }];
}

- (void)handleGoodsResult:(NSDictionary *)dic {
    NSInteger code = [[dic objectForKey:@"code"] integerValue];
    NSString *msg = [dic objectForKey:@"msg"];
    if (code == 1) {
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        // Banner
        NSDictionary *bannerDic = [dataDic objectForKey:@"banner"];
        self.banner = [MWBanner mj_objectWithKeyValues:[bannerDic objectForKey:@"z_info"]];
        
        // Product
        NSDictionary *productDic = [dataDic objectForKey:@"product"];
        NSArray *tempArray = [MWGoods mj_objectArrayWithKeyValuesArray:productDic];
        NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
        [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
        [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
        [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
        
        [[MWNetworkManager manager] POST:kHomeAboutUrl parameters:paraDic progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nonnull responseObject) {
            self.contentString = responseObject[@"data"][@"content"];
            [self.images removeAllObjects];
            [self.images addObject:responseObject[@"data"][@"image"]];
            //计算html字符串高度
            NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[self.contentString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil];
             
            [htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, htmlString.length)];
             
            CGSize textSize = [htmlString boundingRectWithSize:(CGSize){[UIScreen mainScreen].bounds.size.width - 32, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
            
            if (textSize.height == 0) {
                self.aboutMyCollectionReusableViewHeight = 40 + textSize.height + 150;
            } else {
                self.aboutMyCollectionReusableViewHeight = 130 + textSize.height + 150;
            }
            if (self.requestMode == MWRequestModeRefresh) {
                [self.collectionView.mj_header endRefreshing];
                [self.goodsArray removeAllObjects];
                if (tempArray.count == self->_size) {
                    self.collectionView.mj_footer.hidden = NO;
                }
                
            } else {
                if (tempArray.count < self->_size) {
                    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [self.collectionView.mj_footer endRefreshing];
                }
            }
            
            [self.goodsArray addObjectsFromArray:tempArray];
            self.cellHeight = [self calculateCellHeight];
            [self.collectionView reloadData];

        } failure:^(NSError * _Nonnull error) {
            NSLog(@"error = %@", error);
        }];
        
    } else {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = msg;
        [hud hideAnimated:YES afterDelay:2];
    }
}


- (NSMutableArray *)images {
    if (_images == nil) {
        _images = [NSMutableArray array];
    }
    return _images;
}

#pragma mark - 请求筛选数据
- (void)loadHomeFilter {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];

    [[MWNetworkManager manager] POST:kFilterUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        if (code == 1) {
            NSArray *tempArray = [MWFilterModel mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            [self.filterArray addObjectsFromArray:tempArray];
        }
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark -
- (void)uploadLog:(NSString *)content {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:[MWUserManager manager].user.token forKey:@"token"];
    [paraDic setObject:content forKey:@"content"];

    [[MWNetworkManager manager] POST:kLogUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)showFilterMenuView {
    if (!_filterView) {
        _filterView = [[MWFilterMenuView alloc] init];
    }
    [_filterView setContentArray:self.filterArray];
    MWWeakSelf
    _filterView.selectBlock = ^() {
        [weakSelf updateGoodsList];
    };
    
    _filterView.resetBlock = ^{
        weakSelf.filterStr = @"";
        [weakSelf.collectionView.mj_header beginRefreshing];
    };
    
    [_filterView show];
}

- (void)updateGoodsList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (MWFilterModel *model in self.filterArray) {
        NSString *ids = @"";
        for (MWAttribute *attr in model.attr_list) {
            if (attr.isSelected) {
                ids = [NSString stringWithFormat:@"%@,%ld", ids, (long)attr.mid];
            }
        }
        if (ids.length > 0) {
            ids = [ids substringFromIndex:1];
            [dic setObject:ids forKey:[NSString stringWithFormat:@"%ld", (long)model.mid]];
        }
    }
    
    if (dic.count == 0) {
        _filterStr = @"";
    } else {
        _filterStr = [NSString convertJSONWithDic:dic];
    }
    [_collectionView.mj_header beginRefreshing];
}

#pragma mark - 版本检查
- (void)checkVersion {
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:@"苹果熙然版" forKey:@"version_sign"];
    
    MWWeakSelf
    [[MWNetworkManager manager] POST:kCheckVersionUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            [self showVersion:[dic objectForKey:@"data"]];
        }
        
    } failure:^(NSError *error) {
        
    }];
}

- (void)showVersion:(NSDictionary *)dic {
    NSString *version = [dic objectForKey:@"newversion"];
    if (![self isNewVersion:version]) {
        return;
    }
    
    NSString *title = [NSString stringWithFormat:@"发现新版本：%@", version];
    NSString *content = [dic objectForKey:@"content"];
    NSString *downloadUrl = [dic objectForKey:@"downloadurl"];
    NSInteger enforce = [[dic objectForKey:@"enforce"] integerValue];

    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"稍后再说" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
         
    }];
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"现在升级" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *appStoreURL = downloadUrl;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreURL] options:@{} completionHandler:^(BOOL success) {
            
        }];
    }];
    if (enforce == 1) {
        [alertController addAction:updateAction];
    } else {
        [alertController addAction:cancleAction];
        [alertController addAction:updateAction];
    }
   
    [self presentViewController:alertController animated:YES completion:nil];
}

-(BOOL)isNewVersion:(NSString *)version {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSArray *currentVesionArray = [currentVersion componentsSeparatedByString:@"."];
    
    NSArray *versionArray = [version componentsSeparatedByString:@"."];
    
    NSInteger a = (versionArray.count > currentVesionArray.count) ? currentVesionArray.count : versionArray.count;
    
    for (int i = 0; i< a; i++) {
        NSInteger a = [versionArray[i] integerValue];
        NSInteger b = [currentVesionArray[i] integerValue];
        if (a > b) {
            return YES;
        } else if(a < b) {
            return NO;
        }
    }
    return NO;
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        collectionView.hidden = YES;
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        collectionView.hidden = NO;
    }

    
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 0;
    }
    return self.goodsArray.count;
}

- (void)refresh {
    [super refresh];
    [self loadHomeFilter];
    [_collectionView.mj_header beginRefreshing];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    MWHomeHeaderView *headerView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        if (indexPath.section == 2) {
            headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MWGoodsHeaderView" forIndexPath:indexPath];
            
            headerView.block = ^{
                [self showFilterMenuView];
            };
            headerView.titleStr = [[MWConfigManager manager] objectForKey:@"goods_list" defaultValue:@"商品列表"];
            headerView.filterStr = [[MWConfigManager manager] objectForKey:@"shuaixuan" defaultValue:@"筛选"];
        } else if (indexPath.section == 1) {
            AboutMyCollectionReusableView *aboutMyCollectionReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"AboutMyCollectionReusableView" forIndexPath:indexPath];
            aboutMyCollectionReusableView.contentString = self.contentString;
            aboutMyCollectionReusableView.images = self.images;
            aboutMyCollectionReusableView.delegate = self;
            return aboutMyCollectionReusableView;
        }
    }
    return headerView;
}

- (void)lookMore {
    MWAboutController *controller = [[MWAboutController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"MWBannerCell";
        MWBannerCell *bannerCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        if (_banner) {
            [bannerCell configUrlArray:_banner.banner];
        }
        return bannerCell;
        
    } else {
        static NSString *identifier = @"MWGoodsCell";
        MWGoodsCell *goodCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        [goodCell setupData:self.goodsArray[indexPath.row]];
        return goodCell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([[MWConfigManager manager].productType isEqualToString:@"0"]) {
        MWGoods *goods = self.goodsArray[indexPath.row];
        MWGoodsDetailsController *controller = [[MWGoodsDetailsController alloc] init];
        controller.productId = [NSString stringWithFormat:@"%ld", (long)goods.mid];
        [self.navigationController pushViewController:controller animated:YES];
        
    } else {
        if ([MWUserManager manager].user.mid == 2) {
            MWPasswordLoginController *controller = [[MWPasswordLoginController alloc] init];
            [self.navigationController pushViewController:controller animated:YES];
            
        } else {
            MWGoods *goods = self.goodsArray[indexPath.row];
            MWGoodsDetailsController *controller = [[MWGoodsDetailsController alloc] init];
            controller.productId = [NSString stringWithFormat:@"%ld", (long)goods.mid];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 11;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
        return UIEdgeInsetsMake(16, 16, 10, 16);
    }
    return UIEdgeInsetsMake(0, 16, 0, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 2) {
        return CGSizeMake(kScreenWidth, 40);
    } else if (section == 1) {
        return CGSizeMake(kScreenWidth, self.aboutMyCollectionReusableViewHeight);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth - 32, 150);
    }
    return CGSizeMake((kScreenWidth - 47) / 2, _cellHeight);
}

#pragma mark - 计算cell 高度
- (CGFloat)calculateCellHeight {
    CGFloat imgH = 120.0f;
    CGFloat titleH = 22.0f;
    CGFloat priceH = 0;
    CGFloat attrH = 0.0f;
    
    for (MWGoods *goods in self.goodsArray) {
        if (!goods.shuxing) {
            break;
        }
        
        if (goods.price) {
            priceH = 22.0f;
        }
        
        if (attrH < goods.shuxing.count * 22) {
            attrH = goods.shuxing.count * 22;
        }
    }
    
    return imgH + 8 + titleH + priceH + attrH;
}


#pragma mark - Setter && Getter
- (NSMutableArray *)goodsArray {
    if (!_goodsArray) {
        _goodsArray = [[NSMutableArray alloc] init];
    }
    return _goodsArray;
}

- (NSMutableArray *)filterArray {
    if (!_filterArray) {
        _filterArray = [[NSMutableArray alloc] init];
    }
    return _filterArray;
}


#pragma mark - UI
- (void)setupPageSubviews {
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 20, 20);
    [searchBtn setImage:[UIImage imageNamed:@"ic_search_white"] forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"ic_search_white"] forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(searchAvtion:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    self.navigationItem.rightBarButtonItem = buttonItem;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    
    [_collectionView registerClass:[MWGoodsCell class] forCellWithReuseIdentifier:@"MWGoodsCell"];
    [_collectionView registerClass:[MWBannerCell class] forCellWithReuseIdentifier:@"MWBannerCell"];
    [_collectionView registerClass:[MWHomeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MWGoodsHeaderView"];
    [_collectionView registerClass:[AboutMyCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"AboutMyCollectionReusableView"];

     
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    MJRefreshNormalHeader *refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshHomeGoods];
    }];
    refreshHeader.stateLabel.hidden = YES;
    _collectionView.mj_header = refreshHeader;
    
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreHomeGoods];
    }];
    refreshFooter.stateLabel.hidden = YES;
    _collectionView.mj_footer.hidden = YES;
    _collectionView.mj_footer = refreshFooter;
}


@end
